package org.znxs.comfriend.utils;

import android.graphics.Rect;
import android.view.View;

import androidx.recyclerview.widget.RecyclerView;

public class GridSpacingItemDecoration extends RecyclerView.ItemDecoration {

    private int spanCount;
    private int spacing;
    private boolean includeEdge;

    public GridSpacingItemDecoration(int spanCount, int spacing, boolean includeEdge) {
        this.spanCount = spanCount;
        this.spacing = spacing;
        this.includeEdge = includeEdge;
    }

    @Override
    public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
        int position = parent.getChildAdapterPosition(view); // item 的位置
        int column = position % spanCount; // 当前列

        if (includeEdge) {
            outRect.left = spacing - column * spacing / spanCount; // 左边距
            outRect.right = (column + 1) * spacing / spanCount; // 右边距

            if (position < spanCount) { // 第一行
                outRect.top = spacing;
            }
            outRect.bottom = spacing; // 下边距
        } else {
            outRect.left = column * spacing / spanCount; // 左边距
            outRect.right = spacing - (column + 1) * spacing / spanCount; // 右边距

            if (position >= spanCount) { // 非第一行
                outRect.top = spacing; // 上边距
            }
        }
    }
}